<?php

/** post styles meta box hook into WordPress */
add_action('admin_init', 'add_post_styles_metabox');

/** Add meta box */
function add_post_styles_metabox() 
{
	add_meta_box( 'custom_sidebar_metabox', __( 'Post Settings', THEME_NAME ), 'custom_sidebar_metabox', 'post', 'normal', 'high' );
	add_meta_box( 'custom_sidebar_metabox1', __( 'Page Settings', THEME_NAME ), 'custom_sidebar_metabox', 'page', 'normal', 'high' );
}


function custom_sidebar_metabox()
{
	global $post, $wp_registered_sidebars, $_webnukes;
	
	$sidebars = $wp_registered_sidebars;
	$sidebars[-1] = array('name' => __('No Sidebar', THEME_NAME ) );
	$value = (get_post_meta($post->ID, 'wl_custom_sidebar', true)) ? get_post_meta($post->ID, 'wl_custom_sidebar', true) : 'blog-sidebar';
	$data = get_post_meta($post->ID, 'header_image_meta', true);
	
	if( ! $style = get_post_meta($post->ID, 'post_style', true))
		$style = $_webnukes->get_settings('general_settings', 'blog_style');
	
	$image = $_webnukes->kvalue($data, 'upload_image');
	$title = $_webnukes->kvalue($data,'title');
	$desc = $_webnukes->kvalue($data, 'text');
	$wl_post_meta= get_post_meta($post->ID, 'wl_post_meta', true);
	
	include_once(THEME_PATH.'/libs/meta_boxes_html.php');
}
	
/** save metabox fields */
add_action( 'publish_post', 'save_post_style' );
add_action( 'publish_page', 'save_post_style' );

function save_post_style($post_id) 
{
	global $post, $post_ID, $_webnukes;

	$post_id = $_webnukes->kvalue($_POST, 'post_ID', $post_id);
	
	/** check if current user can edit post */
	if ( ! current_user_can( 'edit_post', $post_id ) ) return;
	
	if(isset($_POST['post_type']) && $_POST['post_type'] == 'post')	update_post_meta( $post_id, 'post_style', $_webnukes->kvalue($_POST, 'post_style') );
	
	$header_image = array('upload_image'=>$_webnukes->kvalue($_POST, 'header_image'), 'title'=>$_webnukes->kvalue($_POST, 'header_title'), 'text'=>$_webnukes->kvalue($_POST, 'header_desc'));
	update_post_meta($post_id, 'header_image_meta', $header_image);
	
	/** Updte the custom sidebar for specific post */
	$_POST['wl_custom_sidebar'] = isset($_POST['wl_custom_sidebar']) ? $_POST['wl_custom_sidebar'] : '';
	update_post_meta( $post_id, 'wl_custom_sidebar', $_POST['wl_custom_sidebar']);
	$_POST['wl_post_meta'] = isset($_POST['wl_post_meta']) ? $_POST['wl_post_meta'] : '';
	update_post_meta($post_id, 'wl_post_meta', $_POST['wl_post_meta']);
}